package com.xb.algorithm.utils.sm4;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xb
 * @descripton: SM4加解密
 * @date 2021/11/27
 */
public class SM4Utils {
    // 默认编码
    private static final String ENCODING = "UTF-8";

    private SM4Utils() {
    }

    /**
     * SM4的ECB模式加密
     *
     * @param plainText 待加密字符串
     * @param secretKey 秘钥
     * @return
     */
    public static String encryptData_ECB(String plainText, String secretKey) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;

            byte[] keyBytes;
            keyBytes = secretKey.getBytes();
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes(ENCODING));
            String cipherText = new BASE64Encoder().encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * SM4的ECB模式解密
     *
     * @param cipherText 待解密字符串
     * @param secretKey  秘钥
     * @return
     */
    public static String decryptData_ECB(String cipherText, String secretKey) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;

            byte[] keyBytes;
            keyBytes = secretKey.getBytes();
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            byte[] decrypted = sm4.sm4_crypt_ecb(ctx, new BASE64Decoder().decodeBuffer(cipherText));
            return new String(decrypted, ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * SM4的CBC模式加密
     * @param plainText 待加密字符串
     * @param secretKey 秘钥（要求十六进制的16位）
     * @param iv 子秘钥（要求十六进制的16位）
     * @return
     */
    public static String encryptData_CBC(String plainText, String secretKey, String iv) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;

            byte[] keyBytes;
            byte[] ivBytes;

            keyBytes = secretKey.getBytes();
            ivBytes = iv.getBytes();

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes(ENCODING));
            String cipherText = new BASE64Encoder().encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * SM4的CBC模式解密
     * @param cipherText 待解密字符串
     * @param secretKey 秘钥（要求十六进制的16位）
     * @param iv 子秘钥（要求十六进制的16位）
     * @return
     */
    public static String decryptData_CBC(String cipherText, String secretKey, String iv) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;

            byte[] keyBytes;
            byte[] ivBytes;
            keyBytes = secretKey.getBytes();
            ivBytes = iv.getBytes();

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, new BASE64Decoder().decodeBuffer(cipherText));
            return new String(decrypted, ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws IOException {
        String plainText = "ssda撒打飞机了ii&$$^##)*&6223';.,[]";
        String secretKey = "11HDESaAhiHHugDz";
        plainText.getBytes(ENCODING);
        System.out.println("ECB模式");
        String cipherText = encryptData_ECB(plainText, secretKey);
        System.out.println("密文: " + cipherText);
        System.out.println("");

        plainText = decryptData_ECB(cipherText, secretKey);
        System.out.println("明文: " + plainText);
        System.out.println("");
        System.out.println("CBC模式");
        String iv = "UISwD9fW6cFh9SNS";
        cipherText = encryptData_CBC(plainText, secretKey, iv);
        System.out.println("密文: " + cipherText);
        System.out.println("");

        plainText = decryptData_CBC(cipherText, secretKey, iv);
        System.out.println("明文: " + plainText);
    }

}
